package com.example.zhaohang.myapplication;

import android.app.Application;
import android.content.Context;
import android.os.Process;

import com.squareup.leakcanary.LeakCanary;
import com.squareup.leakcanary.RefWatcher;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;

/**
 * Created by 赵航 on 2017/11/19.
 */

public class MyApplication extends Application {

    private RefWatcher refWatcher;
    @Override
    public void onCreate() {
        super.onCreate();

        //获取全局未捕获的异常
        Thread.setDefaultUncaughtExceptionHandler(new MyUncaghtHandler());
        refWatcher = LeakCanary.install(this);
    }

    public class MyUncaghtHandler implements Thread.UncaughtExceptionHandler {

        @Override
        public void uncaughtException(Thread thread, Throwable throwable) {
            //1.出现了错误保证不能出现xxx报错信息，直接闪退
            Process.killProcess(Process.myPid());
            //2.出现错误时将信息保存在sdk

            try {
                File errFile = new File(getExternalCacheDir().getAbsolutePath(), "err.text");
                PrintStream err = new PrintStream(errFile);
                throwable.printStackTrace(err);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            //3,第二次打开应用时，直接将错误文件上传到服务器


        }
    }
    public static RefWatcher getRefWatcher(Context context) {
        MyApplication application = (MyApplication) context.getApplicationContext();
        return application.refWatcher;
    }

}
